<template>
  <div class="container">
    <div class="content">
      <div class="image-list">
        <img
            v-for="image in images.slice(currentPage * 18, (currentPage + 1) * 18)"
            :key="image"
            :src="image"
            @click="confirmUpload(image)"
            alt=""/>
      </div>
      <div class="buttons">
        <label for="file-upload" class="custom-file-upload">
          选择图片
        </label>
        <input id="file-upload" type="file" accept="image/*" multiple @change="uploadImages"/>
        <button v-if="currentPage > 0" @click="currentPage--" class="custom-file-upload">上一页</button>
        <button v-if="currentPage < Math.ceil(images.length / 18) - 1" @click="currentPage++"
                class="custom-file-upload">下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      images: [],
      currentPage: 0,
    };
  },
  methods: {
    async uploadImages(e) {
      const files = e.target.files;
      for (let i = 0; i < files.length; i++) {
        const formData = new FormData();
        formData.append('files', files[i]);
        const res = await axios.post('http://localhost:9095/api/upload', formData);
        this.images.unshift(`http://localhost:9095/api/images/${res.data[i]}`);
      }
    },
    confirmUpload(image) {
      if (window.confirm('是否确定上传该图片')) {
        this.$emit('uploadImage', image);
      }
    },
    async loadImages() {
      const res = await axios.get('http://localhost:9095/api/list');
      this.images = res.data.map(filename => `http://localhost:9095/api/images/${filename}`);
    },
  },
  created() {
    this.loadImages();
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.content {
  display: flex;
  justify-content: space-between;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 20px;
  max-width: 1300px;
}

.image-list img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  cursor: pointer;
}

.buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.custom-file-upload {
  display: inline-block;
  padding: 10px 18px;
  cursor: pointer;
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
}

.custom-file-upload:hover {
  background-color: #45a049;
}

#file-upload {
  display: none;
}
</style>